package com.esproject.esFactory;

import com.esproject.Config.ESConfig;
import com.google.common.collect.Lists;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.JestResult;
import io.searchbox.client.config.ClientConfig;
import io.searchbox.client.config.ClientConstants;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.DeleteIndex;
import io.searchbox.indices.PutMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.concurrent.*;

/**
 * JestClient方式
 *
 * Created by yan_li on 2017/2/17.
 */
public class JestClietnFactory {

    //Mapping
    public final static String ES_SNS_OPERATION_MAP =
            "{\"cv_data\":"
                    + "{"
                    + "\"dynamic\":true,"
                    + "\"properties\":"
                    + "{"
                    + "\"college\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"expJob\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"expect_city\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"leastcom\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"leastjob\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"major\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"name\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"cuid\":{\"type\":\"string\",\"index\":\"not_analyzed\"},"
                    + "\"cvid\":{\"type\":\"string\",\"index\":\"not_analyzed\"},"
                    + "\"months\":{\"type\":\"string\",\"index\":\"not_analyzed\"},"
                    + "\"edu\":{\"type\":\"string\",\"index\":\"not_analyzed\"}"
                    + "}"
                    + "}"
                    + "}";
    private final static Logger LOG = LoggerFactory.getLogger(JestClietnFactory.class);
    private final static Boolean ES_IS_MULTI_THREADED = true;
    private JestClietnFactory() {

    }
    //根据URL初始化配置
    public static ClientConfig initEsConfig(String url) {
        LinkedHashSet<String> servers = new LinkedHashSet<String>();
        ClientConfig clientConfig = new ClientConfig();
        servers.add(url);
        clientConfig.getProperties().put(ClientConstants.SERVER_LIST, servers);
        clientConfig.getProperties().put(ClientConstants.IS_MULTI_THREADED, ES_IS_MULTI_THREADED);
        return clientConfig;
    }

    //创建client执行方法
    private static JestClient createClient(String url) {
        JestClientFactory factory = new JestClientFactory();
        factory.setClientConfig(initEsConfig(url));
        JestClient client = factory.getObject();
        return client;
    }
    //内部类单利
    private static class ClientHolder {
        private static JestClient client = createClient(ESConfig.HTTPESURL);
    }
    //对外获取方法
    public static JestClient getClient() {
        return ClientHolder.client;
    }

    //创建Mapping
    public static void putMapping(String idxName, String idxType, String map) {
        PutMapping putMapping = new PutMapping(idxName, idxType, map);
        JestClient client = JestClietnFactory.getClient();
        JestResult result = null;
        try {
            result = client.execute(putMapping);
            client.shutdownClient();
        } catch (Exception e) {
            e.printStackTrace();
        }
        LOG.info("putMapping [{}] result:{}", idxName, result.getJsonString());
        System.out.println("putMapping [{" + idxName + "}] result:{" + result.getJsonString() + "}");
    }

    //创建索引
    public static void createIndex(String idxName) {
        CreateIndex createIndex = new CreateIndex(idxName);
        JestClient client = JestClietnFactory.getClient();
        JestResult result = null;
        try {
            result = client.execute(createIndex);
            System.out.println(result.getJsonMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除索引
    public static void deleteIndex(String idxName) throws Exception {
        DeleteIndex deleteIndex = new DeleteIndex(idxName);
        JestClient client = JestClietnFactory.getClient();
        JestResult result = client.execute(deleteIndex);
        LOG.info("deleteIndex [{}] result:{}", idxName, result.getJsonString());
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //createIndex("cv_test", "http://192.168.1.114:9200/");
        //putMapping("cv_test", "cv_data", ES_SNS_OPERATION_MAP);
        ExecutorService pool  = Executors.newFixedThreadPool(3);
        List<Future<JestClient>> list = Lists.newArrayList();
        for(int i=0;i<4;i++){
            Future<JestClient> submit = pool.submit(new Callable<JestClient>() {
                public JestClient call() throws Exception {
                    JestClient client = JestClietnFactory.getClient();
                    System.out.println(Thread.currentThread().getName() + "--->" + System.currentTimeMillis() + "---" + client);
                    return client;
                }
            });
            list.add(submit);
        }
        for(Future<JestClient> fut:list){
            System.out.println(Thread.currentThread().getName()+"---"+fut.get());
        }


    }
}